/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : event_list.js                                 
*  Description  : 자선예약 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-07-10  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 상단탭
	function clsTopTab()
	{
		this._HTMLDom = null;
		this.idx = null;
		
		this._init();
	}
	
	clsTopTab.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content article.depth2_tab");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setIdx(0);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setIdx: function(n){
			this.idx = n;
			this.display();
		}
		, display: function(){
			if(this.idx == null) return;
			
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("img").each(function(){
				$(this).attr("src", $(this).attr("src").replace("_on", ""));
			});
			
			var $i = $layer.find("img").eq(this.idx);
			$i.attr("src", $i.attr("src").replace(".gif", "_on.gif"));
		}
		, getIdx: function(){
			return this.idx;
		}
	}
	
	// 자선예약 리스트
	function clsEventList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsEventList.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("dl:first, table:first").clone(true)
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			if(this.listData.length){
				$layer.find("article.board_list_none").hide();
			}else{
				$layer.find("article.board_list_none").show();
			}
			
			$layer.find("dl, table").remove();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("article.depth2_tab").after($element.clone(true));
			}
			
			$layer.find("dl").each(function(n){
				var d = thisClass.listData[n];
				
				$(this).find("dd:eq(0)").html(d["시작일"] + "~" + d["종료일"]);
				$(this).find("dd:eq(1)").html(d["당첨자발표일"]);
			});
			
			$layer.find("table tbody tr").each(function(n){
				var d = thisClass.listData[n];
				var bEnd = false;
				
				if(d["종료일"]){
					var a = d["종료일"].split(".");
					
					if(a[0].trim() && a[1].trim() && a[2].trim()){
						var nd = new Date(a[0].trim(), a[1].trim()-0-1, a[2].trim()-0+1);
						var now = new Date();
						
						if(nd.getTime() < now.getTime()) bEnd = true;
					}
				}
				
				$(this).find("td:eq(0)").html(d["라운드날짜"] + "(" + d["라운드요일"] + ")");
				$(this).find("td:eq(1)").html("<em>" + d["골프장명"] + "</em> " + d["코스명"]);
				$(this).find("td:eq(2)").html(d["홀"]);
				$(this).find("td:eq(3)").html(_util.number_format(d["1인그린피"]));
				$(this).find("td:eq(4)").html(d["티타임"]);
				$(this).find("td:eq(5)").html(d["참여인원"] + "<span>명</span>");
				
				if(bEnd){
					$(this).find("td.btn").find("img").hide().end().append("마감");
				}
			});
		}
		, spinStart: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.children("dl, table").hide();
			if($layer.find("div#tmpSpin").length == 0){
				$layer.find("article.depth2_tab").after("<div id='tmpSpin' style='position:relative; width:700px; height:100px;' />");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("div#tmpSpin").hide().spin(false);
			$layer.children("dl, table").show();
		}
		, getReserveKey: function(n){
			return this.listData[n]["예약코드"];
		}
	}
	
	function clsComm()
	{
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			
		}
		// 자선예약 목록
		, getEventList: function(arg){
			var thisClass = this;
			
			arg = arg || {};
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "DonationMainReservList";
			if(arg["내꺼"]) serviceName = "DonationMyMainReservList";
			var options = {
				
			}
			_gf.ajax({
				"sid": "DR001"
				, "servicename": serviceName
				, "listcount": arg["페이지당수"]
				, "currpageno": arg["페이지"]
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수": ret["msp"]["contents"]["@totalcount"]
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						res["결과값"].push({
							"예약코드": _util.nvl(obj["reserveSeq"])
							, "시작일": _util.nvl(obj["startDt"])
							, "종료일": _util.nvl(obj["endDt"])
							, "당첨자발표일": _util.nvl(obj["publicDate"])
							, "라운드날짜": _util.nvl(obj["reservDate"])
							, "라운드요일": _util.nvl(obj["bookingDay"])
							, "골프장명": _util.nvl(obj["golfClubNm"])
							, "코스명": _util.nvl(obj["courseInfoNm"])
							, "홀": _util.nvl(obj["holeCnt"])
							, "1인그린피": _util.nvl(obj["greenFee"])
							, "티타임": _util.nvl(obj["bookingTime"])
							, "참여인원": _util.nvl(obj["applyCnt"], 0)
						});
					}
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objBookingControl = null;
		this.objTopTab = null;
		this.eventList = null;
		this.objEventPaging = null;
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objBookingControl = new clsBookingControl();
			this.objTopTab = new clsTopTab();
			this.objEventList = new clsEventList();
			this.objEventPaging = new _gf.clsPaging($("div#idEventPaging"), 10, 10);
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
			
			// 페이징 설정
			$("ul.pagenum_area").wrap("<div id='idEventPaging' />");
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				"좌메뉴": false
			}
			
			_util.executeThread(function(){
				return thisClass.objBookingControl.isLoad();
			}, function(){
				thisClass._permitStart["좌메뉴"] = true;
			});
			
			_util.executeThread(function(){
				for(var key in thisClass._permitStart){
					if(!thisClass._permitStart[key]) return false;
				}
				
				return true;
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			// 상단탭
			this.objTopTab.$getLayer().on("click", "img", function(){
				var n = thisClass.objTopTab.$getLayer().find("img").index($(this));
				var cur = thisClass.objTopTab.getIdx();
				
				if(n != cur){
					document.location.href = "event_list.html" + ((n) ? "?q_my=Y":"");
				}
			});
			
			// 예약신청
			this.objEventList.$getLayer().on("click", "img[alt='예약신청']", function(){
				var n = thisClass.objEventList.$getLayer().find("img[alt='예약신청']").index($(this));
				var reserveKey = thisClass.objEventList.getReserveKey(n);
				
				thisClass.goViewPage(reserveKey);
			});
			
			// 페이지이동
			$(this.objEventPaging).bind("evtPageClick", function(){
				thisClass.searchList();
			});
		}
		, _start: function(){
			this.objBookingControl._start(this, true);
			this.objBookingControl.setReserveType(1);
			
			var q_page = _util.getParam("q_page");
			var q_my = _util.getParam("q_my");

			// 상단탭
			if(q_my == "Y") this.objTopTab.setIdx(1);
			
			this.objEventPaging.setPage((q_page) ? q_page:1);

			this.searchList();
		}
		// 리스트검색
		, searchList: function(){
			var thisClass = this;
			var my = this.objTopTab.getIdx() || "";
			
			this.objEventList.spinStart();
			this.objComm.getEventList({
				"페이지당수": this.objEventPaging.getCountPerPage()
				, "페이지": this.objEventPaging.getPage()
				, "내꺼": my
				, "콜백": function(ret){
					thisClass.finishEventList(ret);
				}
			});
		}
		// 자선예약목록 완료
		, finishEventList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objEventList.spinEnd();
			
			this.objEventPaging.setTotalCount(ret["전체수"]);
			this.objEventPaging.display();
			this.objEventList.setList(ret["결과값"]);
		}
		, getParams: function(){
			var params = {
				"q_page": this.objEventPaging.getPage()
				, "q_my": _util.getParam("q_my")
			}
			
			return params;
		}
		// 상세페이지 이동
		, goViewPage: function(q_seq){
			var p = this.getParams();
			p["q_seq"] = q_seq;
			
			var szLink = _ROOT + "/booking/event_app.html" + _util.object2paramString(p);
			var r = _gf.authCheck(szLink, false);
			if(!r["결과"]){
				if(confirm(_LOGIN_TEXT)){
					_gf.goLogin(szLink);
				}
				
				return;
			}
			
			document.location.href = szLink;
		}
	}
	
	$.ajax({
		url: _ROOT + "/booking/js/booking_common.js"
		, type: "get"
		, dataType: "script"
		, async: false
		, success: function(ret){
			document.objControl = new clsControl();
			document.objControl._init();
		}
		, error: function(){
			alert("error");
		}
	});
});